package com.cofi.vueelementadminserver.config.security;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cofi.vueelementadminserver.entity.system.StmUser;
import com.cofi.vueelementadminserver.mapper.StmUserMapper;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author xyh
 * @date 2024-11-29
 * @description security配置类
 */
@Service
public class SecurityUserDetailsService implements UserDetailsService {

    private final StmUserMapper userMapper;

    public SecurityUserDetailsService(StmUserMapper userMapper){
        this.userMapper = userMapper;
    }

    /**
     * 实现接口方法
     * @param username 用户名
     * @return 用户信息
     * @throws UsernameNotFoundException 用户未找到异常
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaQueryWrapper<StmUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StmUser::getLogName, username);
        StmUser user = userMapper.selectOne(queryWrapper);
        if(ObjectUtils.isEmpty(user)){
            throw new UsernameNotFoundException(username);
        }
        return setUserDetail(user);
    }

    /**
     * 根据用户表，设置UserDetail相关属性
     * @param user 数据库用户表实体
     */
    public SecurityUserDetail setUserDetail(StmUser user) {
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        GrantedAuthority grantedAuthority1 = new SimpleGrantedAuthority("ADMIN");
        GrantedAuthority grantedAuthority2 = new SimpleGrantedAuthority("SUB_ADMIN");
        GrantedAuthority grantedAuthority3 = new SimpleGrantedAuthority("TEACHER");
        grantedAuthorities.add(grantedAuthority1);
        grantedAuthorities.add(grantedAuthority2);
        grantedAuthorities.add(grantedAuthority3);
        SecurityUserDetail userDetail = new SecurityUserDetail(user.getUserName(),
                user.getPwd(),
                true,
                true,
                true,
                true,
                grantedAuthorities);
        userDetail.setId(user.getUserId());
        userDetail.setGradleName("七");
        userDetail.setClassName("5");
        userDetail.setTokenKey("admin-token");
        userDetail.setLogName(user.getLogName());
        userDetail.setNickName(user.getNickName());
        userDetail.setUserPostName(user.getLogName());
        return  userDetail;
    }
}
